﻿using UnityEngine;
using System.Collections;

namespace net {
	public class NetBomb : MonoBehaviour {
		// Bullet传入的参数
		public int direction;
		public GameObject tank;
		protected bool isFromPlayer;
		
		float speed = 10f;
		bool isFlying = true;
		//bool hasDestroyed = false;
		float bombDelay = 0.25f;
		
		AudioSource audioSource;
		Animator anim;
		GameObject target;
		Config cfg;
		
		bool dontCheck ;

		// fix 爆炸后残留bug
		Vector3 lastPos = Vector3.zero;
		float stopTime = 0;
		
		
		// Use this for initialization
		void Start () {
			audioSource = GetComponent<AudioSource> ();
			audioSource.clip = Resources.Load("mp3/bomb") as AudioClip;
			anim = GetComponent<Animator> ();
			anim.StopPlayback ();
			dontCheck = false;
			cfg = new Config ();
		}
		
		// Update is called once per frame
		void Update () {
			Vector3 pos = transform.position;
			if (lastPos.x == 0 && lastPos.y == 0 && lastPos.z == 0) {
				lastPos = pos;
			} else {
				if (pos.x == lastPos.x && pos.y == lastPos.y && pos.z == lastPos.z) {
					if (stopTime - 0 < 1e-10) {
						stopTime = Time.time;
					}
					else {
						if (Time.time - stopTime >= 0.9) {
							Network.Destroy(gameObject);
							stopTime = 0;
							lastPos = Vector3.zero;
						}
					}
				}
				else {
					lastPos = pos;
					stopTime = 0;
				}
			}

			// 默认向上
			Vector3 nextPos = new Vector3(pos.x, pos.y + Time.deltaTime * speed, pos.z);
			
			if (direction == Common.UP) {
				// 上
				nextPos = new Vector3(pos.x, pos.y + Time.deltaTime * speed, pos.z);
			}
			else if (direction == Common.DOWN) {
				// 下
				nextPos = new Vector3(pos.x, pos.y - Time.deltaTime * speed, pos.z);
			}
			else if (direction == Common.LEFT) {
				// 左
				nextPos = new Vector3(pos.x - Time.deltaTime * speed, pos.y, pos.z);
			}
			else if (direction == Common.RIGHT) {
				// 右
				nextPos = new Vector3(pos.x + Time.deltaTime * speed, pos.y, pos.z);
			}
			
			if (isFlying) {
				transform.position = nextPos;
			}
		}
		
		void OnTriggerEnter2D(Collider2D c) {
			target = c.collider2D.gameObject;
			
			// print("撞到东西了");
			// 撞到自己穿过去
			if (target.Equals (tank)) {
				return;
			}
			string objName = Common.getObjName (target);
			
			// 炮弹穿不过去
			if (!cfg.canBulletPass(objName)) {
				BoxCollider2D bc = transform.GetComponent<BoxCollider2D> ();
				if (direction == Common.LEFT || direction == Common.RIGHT) {
					bc.size = new Vector2 (0.9f, 1.5f);
				}
				else if (direction == Common.UP || direction == Common.DOWN) {
					bc.size = new Vector2 (1.5f, 0.9f);
				}
				// 子弹穿过  己方  AI
				if (target.tag.StartsWith("TANK_AI") && target.networkView.isMine) {
					return;
				}
				// 己方  AI子弹穿过玩家
				if (!isFromPlayer && target.tag.StartsWith("TANK_PLAYER") && target.networkView.isMine) {
					return;
				}
				// 子弹穿过  己方  子弹
				if ("BULLET".Equals(target.tag) && target.networkView.isMine) {
					return;
				}

				
				// 停止飞行
				isFlying = false;
				// 爆炸声音
				if ("BASE".Equals(target.tag)&&(!(!isFromPlayer&&networkView.isMine))) {
					networkView.RPC("playFail",RPCMode.All,target.networkView.viewID);
					networkView.RPC("playVoice",RPCMode.All);
					bombDelay += 0.3f;
				}
				// 子弹消失
				SpriteRenderer sr = transform.GetComponent<SpriteRenderer> ();
				sr.sprite = null;
				// 爆炸动画
				networkView.RPC("playAnmi",RPCMode.All);
				try {
					if(isFromPlayer){

						tank.transform.GetComponent<NetPlayerState>().readyToFire = true;
					}
					else{
						tank.transform.GetComponent<NetAIState>().readyToFire = true;
					}
				}
				catch(MissingReferenceException ex) {
					// print("我们的装甲被击穿 ");
				}
				
				
				
				if (cfg.canBulletDestroy(objName)) {
					// 销毁自身
					destroyAfterSec(bombDelay);

					// AI子弹打到  己方  基地半墙，爆炸，但不摧毁
					if (!isFromPlayer	// 子弹不是玩家的
					    && target.name.StartsWith("frag")	// 打到了碎片
					    && target.transform.parent.name.StartsWith("half_brick")	// 碎片是基地半墙
					    && target.networkView.isMine) {	// 是己方的
						return;
					}
					if(!isFromPlayer				// 不是来自玩家的
						&& target.tag.Equals("BASE")//打到了基地
					   	&& target.networkView.isMine){//是己方的
							return;
					}
					//子弹打到了玩家
					if (target.tag.StartsWith("TANK_PLAYER")) {
						
						// 有无敌
						if (target.transform.GetComponent<NetPlayerState>().isImmune) {
							//print ("无敌时间，攻击无效");
							return;
						}
						//没有无敌
						//判断有么有护甲
						if(target.transform.GetComponent<NetPlayerState>().armor>0){
print("挡了一点护甲");
							//消耗护甲，攻击无效
							target.transform.GetComponent<NetPlayerState>().armor--;
						//	networkView.RPC("playAnmi",RPCMode.All);
							return;
						}

						// 正在等待复活 || 已经死了，不能再死了
						if (dontCheck || target.transform.GetComponent<NetPlayerState>().isAlive == false) {
							return;
						}


						target.transform.GetComponent<NetPlayerState>().isAlive = false;
						// 复活
						networkView.RPC("callReborn",RPCMode.Others,target.networkView.viewID);
						//GameObject.FindGameObjectWithTag("MainCamera").transform.GetComponent<NetMain>().rebornAfterSec(2);	// 2s后复活
						dontCheck = true;

					}
					//子弹打到AI
					if(target.tag.StartsWith("TANK_AI")){
						if(target.transform.GetComponent<NetAI>().armor>0){
print("AI挡了一点护甲");
							//消耗护甲，攻击无效
							target.transform.GetComponent<NetAI>().armor--;
							//	networkView.RPC("playAnmi",RPCMode.All);
							return;
						}

					}


					// 销毁撞到的东西
					if (target.name.StartsWith("frag") && "brick".Equals(Common.getObjName(target.transform.parent.gameObject))) {
						//Destroy(target);
						// rpc销毁远程
						transform.networkView.RPC("destroyFrag", RPCMode.All, target.transform.parent.networkView.viewID, target.transform.name);
					}
					else {
						Network.Destroy(target);
					}
				}
				else {
					// 销毁自身
					//GameObject.Destroy (transform.gameObject, bombDelay);
					destroyAfterSec(bombDelay);
				}
			}
		}

		void destroyAfterSec(float s) {
			StartCoroutine(destroy(s));
		}
	
		IEnumerator destroy(float s) {

		//	if (!hasDestroyed) {
		//		hasDestroyed = true;
		//	} else {
		//		return false;
		//	}
			yield return new WaitForSeconds(s);
			
			if(networkView.isMine) {
				Network.RemoveRPCs(this.networkView.viewID);
				Network.Destroy(gameObject);
			}
		}
		public void setIsFromPlayer(bool isFromPlayer){
			this.isFromPlayer = isFromPlayer;
		}
	}
}